<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
              <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="学校" prop="deptId">
            <!-- <el-tree-select
              filterable
              clearable
              v-model="queryParams.deptId"
              :data="deptOptions"
              :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
              value-key="deptId"
              placeholder="请选择学校"
              :render-after-expand="false"
              @change="deptChange"
            /> -->
            <el-select v-model="queryParams.deptId" placeholder="请选择学校" clearable :disabled="!(userId === 1 && tenantDisabled)">
              <el-option v-for="item in tenantOptions" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班级" prop="classId">
            <el-select v-model="queryParams.classId" placeholder="请选择班级" clearable>
              <el-option v-for="dict in classOptions" :key="dict.id" :label="dict.className" :value="dict.id"></el-option>
            </el-select>
            <!-- <el-input v-model="queryParams.classId" placeholder="请输入班级" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
          </el-form-item>
          <el-form-item label="毕业年份" prop="graduateYear">
            <el-input v-model="queryParams.graduateYear" placeholder="请输入毕业年份" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="班级开始年度" prop="enrollmentYear">
            <el-input
              v-model="queryParams.enrollmentYear"
              placeholder="请输入班级开始年度"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="区县" prop="district">
            <el-cascader
              clearable
              filterable
              placeholder="省/市/区"
              :options="addRessList"
              :props="cityProps"
              v-model="queryParams.district"
              popper-class="pc-sel-area-cascader"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleAdd" v-hasPermi="['core:student:add']">新增</el-button>
            <el-button type="primary" @click="handleImport">导入</el-button>
            <el-button type="primary" @click="handleExport" v-hasPermi="['core:student:export']">导出</el-button>
            <el-button type="primary" @click="handleExport2" v-hasPermi="['core:student:export']">更新年级</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <h2>学生列表</h2>
      </template>

      <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" v-if="false" />
        <el-table-column label="学号" align="center" prop="stuId" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="sex">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column label="班级开始年度" align="center" prop="enrollmentYear" />
        <el-table-column label="班级" align="center" prop="classId" />
        <el-table-column label="年级" align="center" prop="grade">
          <template #default="scope">
            <dict-tag :options="sys_grade" :value="scope.row.grade" />
          </template>
        </el-table-column>
        <el-table-column label="毕业年份" align="center" prop="graduateYear">
          <template #default="scope">
            <dict-tag :options="core_grad_year" :value="scope.row.graduateYear" />
          </template>
        </el-table-column>

        <el-table-column label="学校" align="center" prop="deptId">
          <template #default="scope">
            {{getTenantById(tenantOptions,scope.row.deptId)}}
          </template>
        </el-table-column>
        <el-table-column label="区县" align="center" prop="district">
          <template #default="scope">
            <!-- 通过 districtId 查找对应的区县名称 -->
            {{ getFullAddress(scope.row.district) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleUpdate(scope.row)" v-hasPermi="['core:student:edit']">编辑</el-button>
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" v-hasPermi="['core:student:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <!-- <el-button type="text" size="small" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link> -->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StudentADD" lang="ts">
import { listStudent, getStudent, delStudent, addStudent, updateStudent } from '@/api/core/student';
import { StudentVO, StudentQuery, StudentForm } from '@/api/core/student/types';
import { listClasses } from '@/api/core/classes';
import { globalHeaders } from '@/utils/request';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { core_grad_year, sys_common_status, sys_user_sex, sys_normal_disable, sys_grade } = toRefs<any>(
  proxy?.useDict('sys_grade', 'core_grad_year', 'sys_common_status', 'sys_user_sex', 'sys_normal_disable')
);
import { getSubjectNameById,getTeacherNameById,getTenantById } from '@/utils/index';
import { listDept } from '@/api/system/dept'; //学校
import { DeptVO } from '@/api/system/dept/types'; //学校
import cityData from '@/assets/json/pca-code.json';
const addRessList = ref(cityData);
const cityProps = reactive({
  emitPath: false,
  value: 'code', //指定选项的值为addresslist对象的code属性
  label: 'name', //指定选项标签为addresslist对象的name属性
  children: 'children' //指定选项的子选项为addresslist对象的children属性
});
const studentList = ref<StudentVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const viewDisabled = ref(false);
const queryFormRef = ref<ElFormInstance>();
const studentFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/core/student/import'
});
const uploadRef = ref<ElUploadInstance>();

// 学校
interface DeptOptionsType {
  deptId: number | string;
  deptName: string;
  children: DeptOptionsType[];
}
const deptOptions = ref<DeptOptionsType[]>([]); //学校
//学校改租户数据
import { useTenantlList } from '@/composables/useSchoolList';
const { tenantOptions, fetchTenantlList,tenantDisabled} = useTenantlList();
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantId = ref(userStore.tenantId)

interface classOptionsType {
  id: number | string;
  className: string;
}
const classOptions = ref<classOptionsType[]>([]); //班级

const initFormData: StudentForm = {
  name: undefined,
  sex: undefined,
  classId: undefined,
  grade: undefined,
  graduateYear: undefined,
  enrollmentYear: undefined,
  deptId: undefined,
  district: undefined,
  stuId: undefined,
  idType: undefined,
  idNo: undefined,
  images: undefined
};
const data = reactive<PageData<StudentForm, StudentQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    sex: undefined,
    classId: undefined,
    grade: undefined,
    graduateYear: undefined,
    enrollmentYear: undefined,
    deptId: undefined,
    district: undefined,
    idNo: undefined,
    images: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    sex: [{ required: true, message: '性别不能为空', trigger: 'change' }],
    classId: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
    grade: [{ required: true, message: '年级不能为空', trigger: 'blur' }],
    graduateYear: [{ required: true, message: '毕业年份不能为空', trigger: 'blur' }],
    enrollmentYear: [{ required: true, message: '班级开始年度不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '学校不能为空', trigger: 'blur' }],
    district: [{ required: true, message: '区县不能为空', trigger: 'blur' }],
    stuId: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
    idType: [{ required: true, message: '证件类型不能为空', trigger: 'change' }],
    idNo: [
      { required: true, message: '证件号码不能为空', trigger: 'blur' },
      { max: 18, message: '证件号码不能超过18位', trigger: 'blur' }
    ],
    images: [{ required: true, message: '照片不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 根据 districtId 查找对应的完整地址路径，跳过市辖区
const getFullAddress = (districtId) => {
  const findDistrict = (list, id, path = []) => {
    for (let item of list) {
      if (item.code === id) {
        path.push(item.name);
        return path.join('/');
      }
      if (item.children && item.children.length > 0) {
        if (item.name !== '市辖区') {
          path.push(item.name);
        }
        const result = findDistrict(item.children, id, path);
        if (result) {
          return result;
        }
        if (item.name !== '市辖区') {
          path.pop(); // 回溯
        }
      }
    }
    return null;
  };

  const address = findDistrict(addRessList.value, districtId);
  return address || '未知';
};
/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '学生导入';
  upload.open = true;
};
// /** 下载模板操作 */
// const importTemplate = () => {
//   proxy?.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
// };
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}
/** 查询学校列表 */
const getSchoolList = async () => {
  const res = await listDept();
  const data = proxy?.handleTree<DeptOptionsType>(res.data, 'deptId');
  if (data) {
    deptOptions.value = data;
  }
};
/** 查询班级列表 */
const getClassList = async (id) => {
  const res = await listClasses({pageNum: 1,pageSize: 100,deptId:id});
  classOptions.value = res.rows; //班级数据
}
//切换学校选择
function deptChange(e){
  //清空班级列表中的值
  queryParams.value.classId = undefined;
  getClassList(e);
}
/** 查询学生信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStudent(queryParams.value);
  studentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  studentFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: StudentVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({ path: '/base/student/panlView/', query: { type: 0 } });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: StudentVO) => {
  const id = row?.id || ids.value[0];
  // router.push('/base/student/add'+id);
  router.push({ path: '/base/student/panlView/', query: { id: id, type: 1 } });
};
const handleView = async (row?: StudentVO) => {
  const id = row?.id || ids.value[0];
  // router.push('/base/student/add'+id);
  // router.push({ path: '/base/student/panlView/', query: { id: id,type: 1 } });
  router.push({ path: '/base/student/panlView/', query: { id: id, type: 2 } });
};

/** 提交按钮 */
const submitForm = () => {
  studentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateStudent(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addStudent(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: StudentVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除学生信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delStudent(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'core/student/export',
    {
      ...queryParams.value
    },
    `student_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  if(!(userId.value === 1 && tenantDisabled.value)){
    // queryParams.value.deptId = getTenantById(tenantOptions.value,tenantId.value)
    queryParams.value.deptId = Number(tenantId.value) ;
  }
  getList();
  getSchoolList();
});
</script>
